import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/map';

import { Teacher, TeacherStudent } from "./interfaces";

/**
 * This class provides the NameList service with methods to read names and add names.
 */
@Injectable()
export class TeacherListService {

    /**
     * The array of initial names provided by the service.
     * @type {Array}
     */
    teachers: Teacher[] = [];

    /**
     * Contains the currently pending request.
     * @type {Observable<Teacher[]>}
     */
    private request: Observable<Teacher[]>;

    /**
     * Creates a new NameListService with the injected Http.
     * @param {Http} http - The injected Http.
     * @constructor
     */
    constructor(private http: Http) {}

    /**
     * Returns an Observable for the HTTP GET request for the JSON resource. If there was a previous successful request
     * (the local names array is defined and has elements), the cached version is returned
     * @return {Teacher[]} The Observable for the HTTP request.
     */
    get(): Observable<Teacher[]> {
        if (this.teachers && this.teachers.length) {
            return Observable.from([this.teachers]);
        }
        if (!this.request) {
            this.request = this.http.get('/assets/teachers.json')
                .map((response: Response) => response.json())
                .map((data: Teacher[]) => {
                    console.log(data);
                    this.request = null;
                    return this.teachers = data;
                });
        }
        return this.request;
    }
}

@Injectable()
export class TeacherChoseService {
    refresh: number;
    teachers: TeacherStudent[] = [];

    private request: Observable<TeacherStudent[]>;

    constructor(private http: Http) {
        this.refresh = 0;
    }

    get(): Observable<TeacherStudent[]> {
        if (this.teachers && this.teachers.length && (new Date().getTime() - this.refresh < 5 * 60 * 1e3) {
            return Observable.from([this.teachers]);
        }
        if (!this.request) {
            this.request = this.http.get('/assets/teacher-student.json')
                .map((response: Response) => response.json())
                .map((data: TeacherStudent[]) => {
                    this.refresh = (new Date()).getTime();
                    this.request = null;
                    return this.teachers = data;
                });
        }
        return this.request;
    }
}